// pages/user/mymer/detail/detail.js
const app = getApp()
const utils = require('../../../../utils/util.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    merchantDetail: {},
    providerList: [],
    signed: [],
    mid: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      mid: options.mid
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getSignDetail(this.data.mid)
    // let _this = this
    // let random = Math.floor(Math.random() * 100)
    // if (random < 45) _this.getSignDetail(_this.data.mid)
    // else _this.error()
  },

  error: function () {
    wx.showLoading({
      title: '加载数据',
    })
    setTimeout(() => {
      wx.hideLoading()
      wx.showToast({
        title: '服务器无响应',
        duration: 3000
      })
    }, 5000)
  },

  getSignDetail: function (mid) {
    let that = this
    app.getAccessToken(app.getPageUrl(getCurrentPages())).then(function (accessToken) {
      wx.request({
        url: app.globalData.hostAPI + '/v1/order-push/detail?access_token=' + accessToken,
        data: {
          id: mid
        },
        success: res => {
          if (res.data.status === 1) {
            wx.request({
              url: app.globalData.hostAPI + '/v1/order-push/sign-list?access_token=' + accessToken,
              data: {
                id: mid
              },
              success: list => {
                const merchantDetail = res.data.data.push_order_detail
                const providerList = list.data.data
                merchantDetail.service_at = utils.formatTimeThr(merchantDetail.service_at,'Y-M-D')
                that.setData({
                  merchantDetail: merchantDetail,
                  providerList: providerList
                })
              }
            })
          }
        }
      })
    })
  },

  /**
   * 
   */
  accounts: function() {
    wx.redirectTo({
      url: '/pages/user/mymer/detail/detail?mid=' + this.data.mid,
    })
  },

  signing: function(e) {
    let _this = this,
        pid = e.currentTarget.dataset.pid,
        signed = []
    app.getAccessToken(app.getPageUrl(getCurrentPages())).then(function (accessToken) {
      wx.request({
        url: app.globalData.hostAPI + '/v1/order-push/sign-up?access_token=' + accessToken,
        data: {
          id: pid
        },
        success: res => {
          if(res.data.status === 1) {
            signed.push(pid)
            _this.setData({
              signed: signed
            })
            _this.getSignDetail(_this.data.mid)
          }
        }
      })
    })
  }
})